package com.weituotian.moudle.admin.service.impl;

import com.weituotian.core.jpa.domain.SimpleSpecification;
import com.weituotian.core.utils.PageInfo;
import com.weituotian.moudle.admin.entity.vo.AdminCommentVo;
import com.weituotian.moudle.admin.service.IAdminCommentService;
import com.weituotian.moudle.common.service.impl.BaseService;
import com.weituotian.moudle.member.dao.ICommentDao;
import com.weituotian.moudle.member.entity.*;
import com.weituotian.system.dao.IBaseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by ange on 2017/4/8.
 */
@Service("AdminCommentService")
@Transactional
public class AdminCommentService extends BaseService<Comment, Integer> implements IAdminCommentService {

    private final ICommentDao commentDao;

    @Autowired
    public AdminCommentService(ICommentDao commentDao) {
        this.commentDao = commentDao;
    }

    @Override
    public void findPageVo(PageInfo<AdminCommentVo> pageInfo) {
        SimpleSpecification<Comment> spec = new SimpleSpecification<Comment>() {

            @Override
            public Predicate toPredicate(Root<Comment> comment, CriteriaQuery<?> query, CriteriaBuilder cb) {

                List<Predicate> predicates = new ArrayList<Predicate>();

                for (Map.Entry<String, Object> entry : pageInfo.getCondition().entrySet()) {
                    String name = entry.getKey();
                    String value = String.valueOf(entry.getValue());
                    if (name.equals("name")) {
                        predicates.add(cb.like(comment.get(Comment_.content), "%" + value + "%"));
                    } else if (name.equals("member")) {
                        String pattern = "%" + value + "%";
                        Path<Member> member = comment.get(Comment_.member);
                        Predicate or = cb.or(cb.like(member.get(Member_.name), pattern), cb.like(member.get(Member_.loginname), pattern));
                        //发送者
                        predicates.add(or);
                    } else {
                        if (name.equals("video")) {
                            //视频
                            predicates.add(cb.like(comment.get(Comment_.video).get(Video_.title), "%" + value + "%"));
                        }
                    }
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        pageInfo.setList(commentDao.findPage(pageInfo, spec));
    }

    @Override
    public IBaseDao<Comment, Integer> getBaseDao() {
        return commentDao;
    }
}
